#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define SERVER_PORT 8000
#define MAX_BUFFER_SIZE 1024

void handle_information(char buffer[])
{
    // 解析DianTP请求
    char *method = strtok(buffer, " ");
    char *url = strtok(NULL, " ");
    char *DianTP_version = strtok(NULL, "\r\n");
    char *cseq_header = strtok(NULL, "\r\n");
    char *session_header = strtok(NULL, "\r\n");
    printf("method: %s\nurl: %s\nDianTP_version: %s\n%s\n%s\n\n", method, url, DianTP_version, cseq_header, session_header);
}

int main()
{
    // 创建服务器socket
    int server_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sock < 0)
    {
        printf("Failed to create socket");
        return -1;
    }

    // 绑定端口号
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    int bind_result = bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (bind_result < 0)
    {
        printf("Failed to bind port");
        return -1;
    }

    // 监听端口
    int listen_result = listen(server_sock, 5);
    if (listen_result < 0)
    {
        printf("Failed to listen port");
        return -1;
    }

    // 接收客户端请求
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    int client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &client_addr_len);
    if (client_sock < 0)
    {
        printf("Failed to accept client connection");
        return -1;
    }

    // 接收客户端请求数据
    char buffer[MAX_BUFFER_SIZE];
    while (1)
    {
        int recv_size = recv(client_sock, buffer, MAX_BUFFER_SIZE, 0);
        if (recv_size <= 0)
        {
            printf("Failed to receive data");
            return -1;
        }
        handle_information(buffer);

        printf("DianTP request received and handled successfully\n");
    }
    // 关闭连接
    close(client_sock);
    close(server_sock);
    return 0;
}